<script lang="ts" setup>
  import { defineProps, ref, watch, defineEmits } from "vue"
  import { getArea } from "@/api/common"

  const props = defineProps(['modelValue','width','onlyProvince','multiple']);
  const emit = defineEmits(['update:modelValue', 'change']);


  const list = ref<any>([])
  const data = ref()
  const areaRef = ref<any>(null)

  if(props.onlyProvince) {
    data.value = props.modelValue || ''
  } else {
    console.log( props.modelValue ,' props.modelValue  props.modelValue ')
    data.value = props.modelValue || []
  }


  getArea({}).then((res)=>{
    list.value = res
  })

  const change = (e)=> {
    emit('update:modelValue',e)
    if(!e) {
      emit('change', "")
    } else {
      emit('change', list.value.filter((i:any)=>e.includes(i.name)).map((i:any)=>{
        return {
          name: i.name,
          code: i.code,
        }
      }))
    }
  }

  const handleChange = (e) => {
    areaRef.value?.getCheckedNodes()
    emit('change',{
      street: {code: areaRef.value?.getCheckedNodes()[0].pathValues[2],name: areaRef.value?.getCheckedNodes()[0].pathLabels[2]},
      city: {code: areaRef.value?.getCheckedNodes()[0].pathValues[1],name: areaRef.value?.getCheckedNodes()[0].pathLabels[1]},
      province: {code: areaRef.value?.getCheckedNodes()[0].pathValues[0],name: areaRef.value?.getCheckedNodes()[0].pathLabels[0]},
      data: e
    })
  }

  watch(
    () => props.modelValue,
    (newVal, oldVal) => {
      console.log(newVal,'newValnewVal')
      data.value = newVal
    }
  )
</script>

<template>
  <el-select v-if="onlyProvince" clearable :style="`width: ${!width ? '200px' : width}`" v-model="data" :multiple="props.multiple" placeholder="请选择" @change="change">
    <el-option v-for="item in list" :label="item.name" :value="item.name"></el-option>
  </el-select>

  <el-cascader v-else ref="areaRef" clearable :style="`width: ${!width ? '200px' : width}`" v-model="data" :options="list" :props="{label:'name',value:'name',children:'childrens'}" @change="handleChange" />
</template>

<style lang="scss" scoped>

</style>
